<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>串口连接测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .control-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        .control-group {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }
        .control-group h3 {
            margin-top: 0;
            color: #495057;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #495057;
        }
        input, select, button {
            width: 100%;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .disconnect-btn {
            background-color: #dc3545;
        }
        .disconnect-btn:hover {
            background-color: #c82333;
        }
        .status-panel {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            margin-bottom: 20px;
        }
        .status-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 8px;
            background: white;
            border-radius: 4px;
        }
        .status-value {
            font-weight: 500;
        }
        .connected {
            color: #28a745;
        }
        .disconnected {
            color: #dc3545;
        }
        .log-panel {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
            max-height: 300px;
            overflow-y: auto;
        }
        .log-entry {
            padding: 5px 0;
            border-bottom: 1px solid #e9ecef;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .log-entry:last-child {
            border-bottom: none;
        }
        .log-timestamp {
            color: #6c757d;
            margin-right: 10px;
        }
        .log-info {
            color: #17a2b8;
        }
        .log-success {
            color: #28a745;
        }
        .log-error {
            color: #dc3545;
        }
        .log-warning {
            color: #ffc107;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔌 串口连接测试工具</h1>
        
        <div class="control-panel">
            <div class="control-group">
                <h3>设备连接</h3>
                <div class="form-group">
                    <label for="portSelect">串口选择:</label>
                    <select id="portSelect">
                        <option value="COM3">COM3</option>
                        <option value="COM4">COM4</option>
                        <option value="COM5" selected>COM5</option>
                        <option value="COM6">COM6</option>
                        <option value="COM7">COM7</option>
                        <option value="COM8">COM8</option>
                    </select>
                </div>
                <button id="connectBtn" onclick="connectDevice()">连接设备</button>
                <button id="disconnectBtn" onclick="disconnectDevice()" class="disconnect-btn" disabled>断开连接</button>
            </div>
            
            <div class="control-group">
                <h3>测试操作</h3>
                <button onclick="testReconnect()">测试重连 (断开后立即重连)</button>
                <button onclick="testMultipleReconnects()">测试多次重连 (5次)</button>
                <button onclick="clearLogs()">清空日志</button>
            </div>
        </div>
        
        <div class="status-panel">
            <h3>连接状态</h3>
            <div class="status-item">
                <span>设备状态:</span>
                <span id="deviceStatus" class="status-value disconnected">未连接</span>
            </div>
            <div class="status-item">
                <span>当前端口:</span>
                <span id="currentPort" class="status-value">-</span>
            </div>
            <div class="status-item">
                <span>连接次数:</span>
                <span id="connectionCount" class="status-value">0</span>
            </div>
            <div class="status-item">
                <span>最后操作:</span>
                <span id="lastOperation" class="status-value">-</span>
            </div>
        </div>
        
        <div class="log-panel">
            <h3>操作日志</h3>
            <div id="logContainer"></div>
        </div>
    </div>

    <script>
        let connectionCount = 0;
        let isConnected = false;
        let currentSessionId = null;
        
        function addLog(message, type = 'info') {
            const logContainer = document.getElementById('logContainer');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.innerHTML = `<span class="log-timestamp">[${timestamp}]</span>${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        function updateStatus(connected, port = null, operation = null) {
            isConnected = connected;
            document.getElementById('deviceStatus').textContent = connected ? '已连接' : '未连接';
            document.getElementById('deviceStatus').className = `status-value ${connected ? 'connected' : 'disconnected'}`;
            
            if (port) {
                document.getElementById('currentPort').textContent = port;
            }
            
            if (operation) {
                document.getElementById('lastOperation').textContent = operation;
            }
            
            document.getElementById('connectBtn').disabled = connected;
            document.getElementById('disconnectBtn').disabled = !connected;
        }
        
        async function connectDevice() {
            const port = document.getElementById('portSelect').value;
            addLog(`尝试连接设备到端口 ${port}...`, 'info');
            
            try {
                const response = await fetch('/api/device/connect', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ port: port })
                });
                
                const result = await response.json();
                
                if (response.ok && result.success) {
                    connectionCount++;
                    document.getElementById('connectionCount').textContent = connectionCount;
                    currentSessionId = result.session_id;
                    updateStatus(true, port, '连接成功');
                    addLog(`✅ 设备连接成功! 会话ID: ${result.session_id}`, 'success');
                } else {
                    updateStatus(false, null, '连接失败');
                    addLog(`❌ 设备连接失败: ${result.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                updateStatus(false, null, '连接异常');
                addLog(`❌ 连接请求异常: ${error.message}`, 'error');
            }
        }
        
        async function disconnectDevice() {
            if (!currentSessionId) {
                addLog('⚠️ 没有活动的会话ID', 'warning');
                return;
            }
            
            addLog('正在断开设备连接...', 'info');
            
            try {
                const response = await fetch(`/api/device/disconnect/${currentSessionId}`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (response.ok && result.success) {
                    updateStatus(false, '-', '断开成功');
                    addLog('✅ 设备已成功断开连接', 'success');
                    currentSessionId = null;
                } else {
                    addLog(`❌ 断开连接失败: ${result.message || '未知错误'}`, 'error');
                }
            } catch (error) {
                addLog(`❌ 断开请求异常: ${error.message}`, 'error');
            }
        }
        
        async function testReconnect() {
            addLog('🔄 开始重连测试...', 'info');
            
            if (isConnected) {
                await disconnectDevice();
                // 等待1秒确保资源释放
                await new Promise(resolve => setTimeout(resolve, 1000));
            }
            
            await connectDevice();
        }
        
        async function testMultipleReconnects() {
            addLog('🔄 开始多次重连测试 (5次)...', 'info');
            
            for (let i = 1; i <= 5; i++) {
                addLog(`--- 第 ${i} 次重连测试 ---`, 'info');
                
                if (isConnected) {
                    await disconnectDevice();
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                
                await connectDevice();
                await new Promise(resolve => setTimeout(resolve, 2000));
            }
            
            addLog('✅ 多次重连测试完成', 'success');
        }
        
        function clearLogs() {
            document.getElementById('logContainer').innerHTML = '';
            addLog('日志已清空', 'info');
        }
        
        // 页面加载时添加欢迎信息
        window.onload = function() {
            addLog('🚀 串口连接测试工具已启动', 'success');
            addLog('💡 提示: 此工具用于测试串口连接和断开功能，特别是重复连接的稳定性', 'info');
        };
    </script>
</body>
</html>